package com.huazi.eduorder.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.huazi.eduorder.entity.TOrder;
import com.huazi.eduorder.entity.TPayLog;
import com.huazi.eduorder.mapper.TPayLogMapper;
import com.huazi.eduorder.service.TOrderService;
import com.huazi.eduorder.service.TPayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huazi.eduorder.utils.HttpClient;
import com.huazi.servicebase.exceptionhandler.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author huazi
 * @since 2021-03-30
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {
    @Autowired
    TOrderService orderService;
    //生成微信支付的二维码
    @Override
    public Map createNative(String memberId,String orderNo) {
        try{
            //1 根据订单号查询订单信息
            List<TOrder> orders = orderService.list(new QueryWrapper<TOrder>()
                    .eq("member_id", memberId)
                    .eq("status",0));
            //2 使用集合map来设置生成二维码需要的参数
            BigDecimal bd=new BigDecimal(0.00);
            for (TOrder to: orders
                 ) {
                bd=bd.add(to.getTotalFee());
            }
            System.out.println("bd="+bd);
            Map m =new HashMap();
            m.put("appid" ,"wx74862e0dfcf69954");
            m.put ("mch_id","1558950191");
            m.put ("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", "购买课程");//课程标题
            m.put ("out_trade_no",orderNo);//订单号
            m.put("total_fee",bd.multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip","127.0.0.1");//域名地址或本机地址
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            m.put("trade_type","NATIVE");//生成二维码的类型

            //3使用复制的工具类 发送httpclient请求，传递参数xml格式，微信支付提供的固定的地址
            HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));//商铺key
            client.setHttps(true);
            client.post();//执行请求发送
            //4 得到发送请求返回结果
            String xml= client.getContent();
            //返回的内容是xml格式，把xml格式转换成map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //最终返回数据的封装
            Map map=new HashMap();
            map.put("out_trade_no",orderNo) ;
            map.put("total_fee",bd);
            map.put("result_code",resultMap.get("result_code"));//返回二维码频作状态码
            map.put("code_url",resultMap.get("code_url"));//二绾码地址
            return map;
        }catch (Exception e){
            throw new MyException("生成二维码信息错误");
        }

    }
    //根据会员id查询支付状态信息
    @Override
    public Map<String, String> queryPayStatus(String memberId,String orderNo) {
        try{
            Map m =new HashMap();
            m.put("appid" ,"wx74862e0dfcf69954");
            m.put ("mch_id","1558950191");
            m.put ("nonce_str", WXPayUtil.generateNonceStr());
            m.put ("out_trade_no",orderNo);//会员id

            //3使用复制的工具类 发送httpclient请求，传递参数xml格式，微信支付提供的固定的地址
            HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");//跟生成二维码地址不一样
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));//商铺key
            client.setHttps(true);
            client.post();//执行请求发送

            //得到返回的内容
            String xml= client.getContent();
            //把xml格式转换成map集合在返回
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            resultMap.put("out_trade_no",memberId);
            return resultMap;
        }catch (Exception e) {
            return null;
        }
    }
    //更新订单状态并且添加订单的日志记录
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //从map获取会员id
        String memberId = map.get("out_trade_no");
        //修改之前先获取本次的所有支付订单
        List<TOrder> orders = orderService.list(new QueryWrapper<TOrder>().eq("member_id", memberId).eq("status",0));
        //根据会员id修改状态
        orderService.orderStatus(memberId);
        //添加订单日志记录
        for (TOrder or: orders
             ) {
            TPayLog tp=new TPayLog();
            tp.setCourseId(or.getCourseId())
                    .setIsDeleted(false)
                    .setMemberId(or.getMemberId())
                    .setOrderNo(or.getOrderNo())
                    .setPayTime(new Date())
                    .setTotalFee(or.getTotalFee())
                    .setTradeState(map.get("trade_state"))
                    .setTransactionId(map. get("transaction_id"))
                    .setAttr(JSONObject.toJSONString(map))
                    .setPayType(1);
            baseMapper.insert(tp);
        }
    }
}
